<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/20
 * Time: 15:16
 */

namespace app\index\controller;

use app\common\controller\Helptype;
use app\common\lib\YopClient3;
use app\common\lib\YopRequest;
use app\common\lib\Util\YopSignUtils;
use think\Config;
use think\Db;
use think\Cookie;
use think\Exception;
use think\Loader;
use think\Request;
use think\Controller;
use app\index\controller\Sms\AliYunSms;
use app\index\service\MerchantService;

class Merchant extends Controller
{

    public function index()
    {
       echo 'Merchant Controller';
    }

    public function get_branch(Request $request)
    {
        $request =  $request->post();
        $data['headBankCode'] = 'CIB';//开户银行总行编码
        $data['provinceCode'] = '310000';//开户省
        $data['cityCode'] = '310100';//开户市
        $result = MerchantService::branch($data);
        var_dump($result);
    }
    /**
     * [get_sms_yb 获取 修改结算卡 手机验证  易宝 ]
     * @author 刘家腾
     * @DateTime 2018-09-30T15:32:58+0800
     * @param    string                   $value [description]
     * @return   [type]                          [description]
     */
    public function get_sms_yb(Request $request)
    {
        $back = ['code'=>666,'msg'=>'ok','data'=>[]];
        $request =  $request->post();
        $data['parentMerchantNo'] = '10024438625';
        $data['merchantNo'] = '10024751765';
        $data['phone'] = '13917758909';
        $data['sourceType'] = 'NET_IN';
        $result = MerchantService::phone_code($data);
        var_dump($result);

    }

    /**
     * [get_modify_billing_card 修改结算卡]
     * @author 刘家腾
     * @DateTime 2018-09-30T17:52:47+0800
     * @param    Request                  $request [description]
     */
    public function get_modify_billing_card(Request $request)
    {
       $back = ['code'=>666,'msg'=>'ok','data'=>[]];
        $request =  $request->post();
        $data['merAuthorizeNum'] = '026937';//验证码
        $data['bankcardNo'] = '216160100100107217';//银行卡号
        $data['headBankName'] = 'CIB';//开户总行编码
        $data['bankName'] = '309290000295';//开户银行分行银行编码
        $data['bankProvince'] = '310000';//开户省
        $data['bankCity'] = '310100';//
        $data['requestNo'] = '8d033a90cf213f9cbfbb0c0c97eebca3';//入网请求号
        
        $data['withdrawType'] = 'SETTLE';//结算卡
        $data['parentMerchantNo'] = '10024438625';
        $data['merchantNo'] = '10024751765';
        //$data['callbackurl'] = ;//商户回调地址

        
        $result = MerchantService::modify_billing_card($data);
        var_dump($result);
    }

    /**
     * @Notes:企业认证
     * @param Request $request
     * @return array
     * @author: LiBaoJin
     * @Time:
     */
    public function merchant_register(Request $request){

        $back = ['code'=>666,'msg'=>'ok','data'=>[]];
        $request =  $request->post();
        $validate = Loader::validate('Merchant');
        $rule = $validate->check($request);
        if($rule !== true){
            $back['code'] = -1;
            $back['msg'] = $validate->getError();
            return $back;
        }
        if($request['merCertType'] == 'UNI_CREDIT_CODE'){
            if(empty($request['fileInfo']['UNI_CREDIT_CODE'])){
                $back['code'] = -1;
                $back['msg'] = '统一社会信用代码证图片没有上传';
                return $back;
            }
        }
        if($request['merCertType'] == 'CORP_CODE'){
            if(empty($request['fileInfo']['CORP_CODE']))
            {
                $back['code'] = -1;
                $back['msg'] = '营业执照图片没有上传';
                return $back;
            }
            if(empty($request['fileInfo']['TAX_CODE'])){
                $back['code'] = -1;
                $back['msg'] = '税务登记证图片没有上传';
                return $back;
            }
            if(empty($request['fileInfo']['ORG_CODE'])){
                $back['code'] = -1;
                $back['msg'] = '组织机构代码证图片没有上传';
                return $back;
            }
            if(empty($request['isOrgCodeLong'])){
                $back['code'] = -1;
                $back['msg'] = '组织机构代理证有效期必须填写';
                return $back;
            }
            if($request['isOrgCodeLong'] != 'true'){
                if(empty($request['orgCodeExpiry'])){
                    $back['code'] = -1;
                    $back['msg'] = '组织机构代理证有效期必须填写';
                    return $back;
                }
            }

        }
        $yeepay = Config::get('yeepay');
        $merchant_identify_email = Config::get('merchant_identify_email');
        $base_image_dir = Config::get('base_image_dir');
        $qiniu_image_dir = Config::get('qiniu')['merchantDomain'];
        try{
            Db::table('merchant')
                ->where(['user_id'=>$this->user_id])
                ->delete();
            Db::table('merchant_resource')
                ->where(['user_id'=>$this->user_id])
                ->delete();
            Db::table('merchant_resource_own')
                ->where(['user_id'=>$this->user_id])
                ->delete();
            Db::table('merchant_resource_yeepay')
                ->where(['user_id'=>$this->user_id])
                ->delete();
            Db::table('merchant_resource_thumb')
                ->where(['user_id'=>$this->user_id])
                ->delete();
           $merchant_id =  Db::name("merchant")->insertGetId([
                'user_id'             =>$this->user_id,
                'requestNo'           =>md5(time()),//入网请求号
                'type'                => 3, // 企业认证
                'parentMerchantNo'    =>$yeepay['parentMerchantNo'],//商户编号
                'merFullName'         =>$request['merFullName'],//商户全称，必须和营业执照上一致
                'merShortName'        =>$request['merShortName'],//商户品牌名称，收银台上显示的商户名
                'merCertType'         =>$request['merCertType'],//证件类型
                'merCertNo'           =>$request['merCertNo'],//证件号
                'legalName'           =>$request['legalName'],//法人姓名
                'legalIdCard'         =>$request['legalIdCard'],//法人身份证号
                'merLevel1No'         =>'102',//商户一级分类编码
                'merLevel2No'         =>'102002',//商户二级分类编码
                'merProvince'         =>$request['merProvince'],//商户经营地址所在省
                'merCity'             =>$request['merCity'],//商户经营地址所在市
                'merDistrict'         =>$request['merDistrict'],//商户经营地址所在区
                'merAddress'          =>$request['merAddress'],//商户经营地址所在具体地址
                'merContactName'      =>$request['merContactName'],//商户联系人姓名
                'merContactPhone'     =>$request['merContactPhone'],//商户联系人手机
                'merContactEmail'     =>$merchant_identify_email,//商户联系人邮箱
                'taxRegistCert'       =>$request['taxRegistCert'],//税务登记证编号 //签约类型为“企业”，且证件类型为 “营业执照”，则必填【可空】
                'accountLicense'      =>$request['accountLicense'],//开户许可证编号
                'orgCode'             =>$request['orgCode'],//组织机构代码证 //签约类型为“企业”，且证件类型为 “营业执照”，则必填【可空】
                'isOrgCodeLong'       =>$request['isOrgCodeLong'],//是否长期有效 【可空】
                'orgCodeExpiry'       =>empty($request['orgCodeExpiry'])?null:$request['orgCodeExpiry'],//组织机构代理证有效期 //签约类型为“企业”，且证件类型为 “营业执照”，则必填 如果为长期有效则不填; 时间格式: YYYY-MM-DD 【可空】
                'cardNo'              =>$request['cardNo'],//银行卡号	【可空】
                'headBankCode'        =>$request['headBankCode'],//开户银行总行编码
                'bankCode'            =>$request['bankCode'],//开户支行编码 bankCode
                'bankProvince'        =>$request['bankProvince'],//开户省
                'bankCity'            =>$request['bankCity'],//开户市
                //'productInfo'          =>'',//开通产品
                'create_time'         =>date('Y-m-d H:i:s',time()),
                'update_time'         =>date('Y-m-d H:i:s',time()),
                'state'               =>0,
                'openMini'            =>$request['openMini'],
               'logo_url' => isset($request['fileInfo']['logo_url']['url']) ? $request['fileInfo']['logo_url']['url'] : null,
            ]);
            if(!$merchant_id){
                $back['code'] = -1;
                $back['msg'] ="系统错误";
                return $back;
            }
            Db::name("merchant_resource")->insert([
                'user_id' => $this->user_id,
                'merchant_id'  =>$merchant_id,
                'IDCARD_FRONT' =>$base_image_dir.$request['fileInfo']['IDCARD_FRONT']['_file'],
                'IDCARD_BACK' =>$base_image_dir.$request['fileInfo']['IDCARD_BACK']['_file'],
                'CORP_CODE' =>isset($request['fileInfo']['CORP_CODE']['_file'])?$base_image_dir.$request['fileInfo']['CORP_CODE']['_file']:null,
                'TAX_CODE' =>isset($request['fileInfo']['TAX_CODE']['_file'])?$base_image_dir.$request['fileInfo']['TAX_CODE']['_file']:null,
                'ORG_CODE' =>isset($request['fileInfo']['ORG_CODE']['_file'])?$base_image_dir.$request['fileInfo']['ORG_CODE']['_file']:null,
                'UNI_CREDIT_CODE' =>isset($request['fileInfo']['UNI_CREDIT_CODE']['_file'])?$base_image_dir.$request['fileInfo']['UNI_CREDIT_CODE']['_file']:null,
                'OP_BANK_CODE' =>$base_image_dir.$request['fileInfo']['OP_BANK_CODE']['_file'],
                //'SETTLE_BANKCARD' =>$base_image_dir.$request['fileInfo']['SETTLE_BANKCARD']['_file'],
                //'HAND_IDCARD' =>$base_image_dir.$request['fileInfo']['HAND_IDCARD']['_file'],
                //'HAND_BANKCARD' =>$base_image_dir.$request['fileInfo']['HAND_BANKCARD']['_file'],
               'state' => 0,
                'create_time'=>date('Y-m-d H:i:s',time()),
                'update_time'=>date('Y-m-d H:i:s',time()),
            ]);

            Db::name("merchant_resource_own")->insert([
                'user_id' => $this->user_id,
                'merchant_id'  =>$merchant_id,
                'IDCARD_FRONT' =>$request['fileInfo']['IDCARD_FRONT']['url'],
                'IDCARD_BACK' =>$request['fileInfo']['IDCARD_BACK']['url'],
                'CORP_CODE' =>isset($request['fileInfo']['CORP_CODE']['url'])?$request['fileInfo']['CORP_CODE']['url']:null,
                'TAX_CODE' =>isset($request['fileInfo']['TAX_CODE']['url'])?$request['fileInfo']['TAX_CODE']['url']:null,
                'ORG_CODE' =>isset($request['fileInfo']['ORG_CODE']['url'])?$request['fileInfo']['ORG_CODE']['url']:null,
                'UNI_CREDIT_CODE' =>isset($request['fileInfo']['UNI_CREDIT_CODE']['url'])?$request['fileInfo']['UNI_CREDIT_CODE']['url']:null,
                'OP_BANK_CODE' =>$request['fileInfo']['OP_BANK_CODE']['url'],
                //'SETTLE_BANKCARD' =>$request['fileInfo']['SETTLE_BANKCARD']['url'],
                //'HAND_IDCARD' =>$request['fileInfo']['HAND_IDCARD']['url'],
                //'HAND_BANKCARD' =>$request['fileInfo']['HAND_BANKCARD']['url'],
               'state' => 0,
                'create_time'=>date('Y-m-d H:i:s',time()),
                'update_time'=>date('Y-m-d H:i:s',time()),
            ]);

            Db::name("merchant_resource_yeepay")->insert([
                'user_id' => $this->user_id,
                'merchant_id'  =>$merchant_id,
                'state' => 0,
                'create_time'=>date('Y-m-d H:i:s',time()),
                'update_time'=>date('Y-m-d H:i:s',time()),
            ]);

            Db::name("merchant_resource_thumb")->insert([
                'user_id' => $this->user_id,
                'merchant_id'  =>$merchant_id,
                'IDCARD_FRONT' =>$request['fileInfo']['IDCARD_FRONT']['thumb'],
                'IDCARD_BACK' =>$request['fileInfo']['IDCARD_BACK']['thumb'],
                'CORP_CODE' =>isset($request['fileInfo']['CORP_CODE']['thumb'])?$request['fileInfo']['CORP_CODE']['thumb']:null,
                'TAX_CODE' =>isset($request['fileInfo']['TAX_CODE']['thumb'])?$request['fileInfo']['TAX_CODE']['thumb']:null,
                'ORG_CODE' =>isset($request['fileInfo']['ORG_CODE']['thumb'])?$request['fileInfo']['ORG_CODE']['thumb']:null,
                'UNI_CREDIT_CODE' =>isset($request['fileInfo']['UNI_CREDIT_CODE']['thumb'])?$request['fileInfo']['UNI_CREDIT_CODE']['thumb']:null,
                'OP_BANK_CODE' =>$request['fileInfo']['OP_BANK_CODE']['thumb'],
                //'SETTLE_BANKCARD' =>$request['fileInfo']['SETTLE_BANKCARD']['thumb'],
                //'HAND_IDCARD' =>$request['fileInfo']['HAND_IDCARD']['thumb'],
                //'HAND_BANKCARD' =>$request['fileInfo']['HAND_BANKCARD']['thumb'],
               'state' => 0,
                'create_time'=>date('Y-m-d H:i:s',time()),
                'update_time'=>date('Y-m-d H:i:s',time()),
            ]);
            
            Db::table('business')->where(['business_id'=>$this->user_id])->update([
                    'is_auth'=>1,
                    'business_name'=>$request['merFullName'],
                    'business_province'=>$request['merProvince'],
                    'business_city'=>$request['merCity'],
                    'business_area'=>$request['merDistrict'],
                    'business_address'=>$request['merAddress'],
                    'license_image_url'=>isset($request['fileInfo']['CORP_CODE']['img'])?$request['fileInfo']['CORP_CODE']['img']:null,

            ]);

            Db::table('users')->where(['id'=>$this->user_id])->update([
                'name'=>$request['merShortName']
            ]);
            Db::table('user_info')->where(['user_id'=>$this->user_id])->update([
                'name'=>$request['merShortName']
            ]);

            Cookie::set('is_auth',1);
            
        }catch(Exception $e){
            $back['code'] = -1;
            $back['msg'] = $e->getMessage();
            return $back;
        }
      return $back;
    }

    /**
     * @param Request $request
     * @return mixed
     * 商户验证文件上传
     */
   public  function file_upload(Request $request){
       $request =  $request->post();
       $yeepay = Config::get('yeepay');
       $req = new YopRequest($yeepay['appKey'],$yeepay['private_key'],$yeepay['head_url'],$yeepay['yop_public_key']);
       $req->addParam("fileType", "IMAGE");
       $req->addParam("_file", $request['fileURI']);
        $response = YopClient3::upload("/file/upload", $req);
       $response=Helptype::object_array($response);
       if( $response['result'] == NULL)
       {
           $back['code'] = -1;
           $back['msg'] = $response['error'];
           return $back;
       }
       $back['data'] = $response['result'];
       return $back;
    }

    /**
     * @param 
     * @return array
     * 发送短信验证码（设置支付密码）
     */
    public function set_pay_password_sms(Request $request)
    {
        $postData = $request->post();
        //验证传过来的参数
        $user = $this->user;
        $code = rand(1000,9999);
        try{
           $data_code = Db::table('phone_code')->where(['phone'=>$user['phone']])->find();
            if(empty($data_code)){
                Db::table('phone_code')->insert(['phone'=>$user['phone'],'code'=> $code,'createtime'=>date('Y-m-d H:i:s')]);
            }else{
                $data = Db::table('phone_code')->where(['phone'=>$user['phone']])->delete();
                if(!$data){
                    ReturnData::error(1001,'系统错误，稍后重试');
                }
                Db::table('phone_code')->insert(['phone'=>$user['phone'],'code'=>$code,'createtime'=>date('Y-m-d H:i:s')]);
            }

        }catch(Exception $e){
             ReturnData::error(1002,$e->getMessage());
        }
        $AliYunSms = new AliYunSms();
        $date = $AliYunSms->code_type($code,'paypassword')->setRecNum($user['phone']);
        return $date;
    }

     /**
     * @param Request $request
     * @return mixed
     * 设置提现密码
     */
    public function set_pay_password(Request $request)
    {
        $postData = $request->post();
        $rules = [
            "pay_password|支付密码"            => "require",
            "re_pay_password|重复支付密码"      => "require",
            "code|手机验证码"                  => "require",
        ];
        $user = $this->user;
        if($this->validate($postData, $rules) !== true){
            return ReturnData::error(1001,$this->validate($postData, $rules));
        }
        if(!preg_match('/^[0-9]{6}$/', $postData['pay_password'])){
            return ReturnData::error(1002, '请输入6位密码，并且必须6位数字！');
        }
        if($postData['pay_password'] != $postData['re_pay_password']){
            return ReturnData::error(1003, '两次密码不一致！');
        }
        $phoneCode = Db::table('phone_code')->where(['phone'=>$user['phone'],'code'=>$postData['code']])->find();
        if($phoneCode == null){
            return ReturnData::error(1004, '手机验证码错误！');
        }
        if( (time()-strtotime($phoneCode['createtime'])) > 5*60 ){
            return ReturnData::error(1005, '手机验证码已失效，请重新发送！');
        }

        $business = Db::table('business')->where(['business_id'=> $this->business_id])->find();
        if($business == null){
            return ReturnData::error(1006, '非商户本人操作！');
        }
        if(Db::table('business')->where(['business_id'=> $this->business_id])->update(['pay_password' => $postData['pay_password']])){
            return ReturnData::ok('支付密码设置成功！');
        }else{
            return ReturnData::error(1007, '支付密码不能与原密码相同！');
        }

    }

    /**
     * @param Request $request
     * @return mixed
     * 商家提现申请
     * author：Jason
     * Date: 2018/09/15
     */
    public function withdraw(Request $request)
    {
        $postData = $request->post();
        $rules = [
            "money|提现金额"            => "require|float",
            "pay_password|支付密码"     => "require",
        ];
        $user = $this->user;
        if($this->validate($postData, $rules) !== true){
            return ReturnData::error(1001,$this->validate($postData, $rules));
        }
        $availableMoney = round(MerchantService::get_balance($user['id'],1),2);
        if((float)$availableMoney < (float)$postData['money']){
            return ReturnData::error(1002,'余额不足！');
        }
        $business = Db::table('business')->where(['business_id'=> $this->business_id])->find();
        if($business == null){
            return ReturnData::error(1003, '非商户本人操作！');
        }
        if($business['pay_password'] == null){
            return ReturnData::error(1004, '该商户未设置支付密码，请先设置！');
        }
        if($business['pay_password'] !== $postData['pay_password']){
            return ReturnData::error(1005, '支付密码错误！');
        }
        if($business['parentMerchantNo'] == null){
            return ReturnData::error(1006, '该商户未设置易宝系统商编！');
        }
        if($business['merchantNo'] == null){
            return ReturnData::error(1006, '该商户未设置易宝商编！');
        }
        $orderId = mt_rand(10000000,99999999).mt_rand(1000000,9999999);
        $data = [
            'parentMerchantNo'  => $business['parentMerchantNo'],
            'merchantNo'        => $business['merchantNo'],
            'orderId'           => $orderId, //商户订单号 15位
            'cashType'          => 'D1', //提现类型:D0,D1
            'feeType'           => 'SOURCE', //SOURCE:付款方手续费/TARGET：收款方手续费
        ];
        $feeRate  = Config::get('withdraw_fee_rate');
        $withdrawMoney = $postData['money']*(1-$feeRate);

        $result = MerchantService::withdrawMoney($data,$withdrawMoney);

        if(isset($result['errorCode']) && $result['errorCode'] == 'BAC400000' ){
            $insertMerchantCurrency = [
                'user_id'               => $this->business_id,
                'withdraw_orderId'      => $orderId,
                'money'                 => sprintf("%.2f",$postData['money']),
                'fee'                   => sprintf("%.2f",$postData['money']*$feeRate),
                'type'                  => 2, //1 进账 2提现
                'state'                 => 1,
                'pay_code'              => 1, // 银行卡方式
                'createtime'            => date('Y-m-d H:i:s'),
                'withdraw_time'         => date('Y-m-d H:i:s'),
            ];
            Db::table('merchant_currency')->insert($insertMerchantCurrency);
            Db::table('merchant_withdraw')->insert(['business_id' => $this->business_id, 'withdraw_orderId'=> $orderId,'amount'=>sprintf("%.2f",$postData['money']),'create_time'=> date('Y-m-d H:i:s')]);
            return ReturnData::ok('提现申请成功！');
        }else{
            $insertMerchantCurrency = [
                'user_id'               => $this->business_id,
                'withdraw_orderId'      => $orderId,
                'money'                 => sprintf("%.2f",$postData['money']),
                'fee'                   => sprintf("%.2f",$postData['money']*$feeRate),
                'type'                  => 2, //1 进账 2提现
                'state'                 => 0,
                'pay_code'              => 1, // 银行卡方式
                'createtime'            => date('Y-m-d H:i:s'),
                'withdraw_time'         => date('Y-m-d H:i:s'),
            ];
            if( Db::table('merchant_currency')->insert($insertMerchantCurrency) ){
                return ReturnData::error(1007,$result['errorMsg'], $result);
            }else{
                return ReturnData::error(1008,'提现失败，稍后重试');
            }
        }
    }

    /**
     * @param Request $request
     * @return mixed
     * 商家提现回调函数
     * author：Jason
     * Date: 2018/10/08
     */
    public function withdraw_notify(Request $request)
    {
        $yeePayConfig   = Config::get('yeepay');
        $data           = $_REQUEST["response"]; 
        $callback       = YopSignUtils::decrypt($data,$yeePayConfig['private_key'], $yeePayConfig['yop_public_key']);
        $postData       = json_decode($callback, true);

        Helptype::yibaoLog(8,'withdraw_notify',$data,$callback);

        $merchantWithdraw = Db::table('merchant_withdraw')
                        ->where(['withdraw_orderId' => $postData['orderId']])
                        ->find();
        if($merchantWithdraw != null)
        {
            $withdrawUpdate = [
                'customerNumber'        => $postData['customerNumber'],
                'groupNumber'           => $postData['groupNumber'],
                'cashType'              => $postData['cashType'],
                'bankAccountNo'         => $postData['bankAccountNo'],
                'bankAccountName'       => $postData['bankAccountName'],
                'bankCardType'          => $postData['bankCardType'],
                'amount'                => $postData['amount'],
                'realAmount'            => $postData['realAmount'],
                'fee'                   => $postData['fee'],
                'feeType'               => $postData['feeType'],
                'requestDate'           => $postData['requestDate'],
                'finishTime'            => $postData['finishTime'],
                'transferStatusCode'    => $postData['transferStatusCode'],
                'bankTrxStatusCode'     => $postData['bankTrxStatusCode'],
                'leaveWord'             => $postData['leaveWord'],
                'update_time'           => date('Y-m-d H:i:s'),
            ];
            $merchantWithdraw = Db::table('merchant_withdraw')
                        ->where(['withdraw_orderId' => $postData['orderId']])
                        ->update($withdrawUpdate);
            if($merchantWithdraw){
                return 'SUCCESS';
            }else{
                Db::table('merchant_withdraw')
                        ->where(['withdraw_orderId' => $postData['orderId']])
                        ->delete();
                $withdrawUpdate['withdraw_orderId'] = $postData['orderId'];
                $withdrawUpdate['create_time']      = date('Y-m-d H:i:s');
                Db::table('merchant_withdraw')->insert($withdrawUpdate);
            }
        }else{
            $withdrawInsert = [
                'withdraw_orderId'      => $postData['orderId'],
                'customerNumber'        => $postData['customerNumber'],
                'groupNumber'           => $postData['groupNumber'],
                'cashType'              => $postData['cashType'],
                'bankAccountNo'         => $postData['bankAccountNo'],
                'bankAccountName'       => $postData['bankAccountName'],
                'bankCardType'          => $postData['bankCardType'],
                'amount'                => $postData['amount'],
                'realAmount'            => $postData['realAmount'],
                'fee'                   => $postData['fee'],
                'feeType'               => $postData['feeType'],
                'requestDate'           => $postData['requestDate'],
                'finishTime'            => $postData['finishTime'],
                'transferStatusCode'    => $postData['transferStatusCode'],
                'bankTrxStatusCode'     => $postData['bankTrxStatusCode'],
                'leaveWord'             => $postData['leaveWord'],
                'create_time'           => date('Y-m-d H:i:s'),
                'update_time'           => date('Y-m-d H:i:s'),
            ];
            $withdrawInsert = Db::table('merchant_withdraw')->insert($withdrawInsert);
            if($withdrawInsert){
                return 'SUCCESS';
            }else{
                Db::table('merchant_withdraw')->insert($withdrawInsert);
            }
        }

    }

    /**
     * @param Request $request
     * @return mixed
     * 商家提现状态查询
     * author：Jason
     * Date: 2018/10/12
     */
    public function getWithdrawState(Request $request)
    {
        $postData = $request->post();
        $merchantWithdraw = Db::table('merchant_currency')
                        ->where(['withdraw_orderId' => $postData['orderId'], 'user_id' => $this->user_id])
                        ->find();
        if($merchantWithdraw == null){
            return ReturnData::error(1001,'查不到该订单');
        }
        $withdrawState = MerchantService::getWithdrawState($this->user_id,$postData['orderId']);

        if($withdrawState['state'] == 'SUCCESS'){
            return ReturnData::ok($withdrawState['result'], '查询成功');
        }
        else{
            return ReturnData::error(1002,'查询失败',$withdrawState);
        }
    }
    /**
     * @Notes:个体商户
     * @param Request $request
     * @return array
     * @author: LiBaoJin
     * @Time:
     */
    public function individual_certification(Request $request) {
        $back = ['code'=>666,'msg'=>'ok','data'=>[]];
        $request = $request->post();
        $validate = Loader::validate('IndividualCertification');
        $rule = $validate->check($request);
        if ($rule !== true) {
            $back['code'] = -1;
            $back['msg'] = $validate->getError();
            return $back;
        }
        $detele_data = MerchantService::delete_data($this->user_id);
        if ($detele_data['code'] != '666') {
            return ReturnData::error($detele_data['code'], $detele_data['msg']);
        }
        Db::startTrans();
        try {
            $yeepay = Config::get('yeepay');
            $merchant_identify_email = Config::get('merchant_identify_email');
            $base_image_dir = Config::get('base_image_dir');
            $merchant_id = Db::name("merchant")->insertGetId([
                'user_id' => $this->user_id,
                'requestNo' => md5(time()), //入网请求号
                'type' => 2, // 个体
                'parentMerchantNo' => $yeepay['parentMerchantNo'], //商户编号
                'merFullName' => $request['merFullName'], //商户全称和营业执照一致
                'merShortName' => $request['merShortName'], //商户品牌名/简称
                'merCertNo' => $request['merCertNo'], //营业执照号
                'legalName' => $request['legalName'], //法人姓名
                'legalIdCard' => $request['legalIdCard'], //法人身份证号
                'merLevel1No' => '102', //商户一级分类编码
                'merLevel2No' => '102002', //商户二级分类编码
                'merLegalPhone' => $request['merLegalPhone'], //商户联系人手机
                'merLegalEmail' => $merchant_identify_email, //商户联系人邮箱
                'merProvince' => $request['merProvince'], //商户经营地址所在省
                'merCity' => $request['merCity'], //商户经营地址所在市
                'merDistrict' => $request['merDistrict'], //商户经营地址所在区
                'merAddress' => $request['merAddress'], //商户经营地址所在具体地址
                'cardNo' => $request['cardNo'], //银行卡号
                'headBankCode' => $request['headBankCode'], //开户银行总行编码
                'bankCode' => $request['bankCode'], //开户支行编码 bankCode
                'bankProvince' => $request['bankProvince'], //开户省
                'bankCity' => $request['bankCity'], //开户市
                'create_time' => date('Y-m-d H:i:s', time()),
                'update_time' => date('Y-m-d H:i:s', time()),
                'state' => 0,
                'openMini' => $request['openMini'],
                'logo_url' => isset($request['fileInfo']['logo_url']['url']) ? $request['fileInfo']['logo_url']['url'] : null,
            ]);
            if (!$merchant_id) {
                return ReturnData::error(-1, '系统错误');
            }
            Db::name("merchant_resource")->insert([
                'user_id' => $this->user_id,
                'merchant_id' => $merchant_id,
                'IDCARD_FRONT' => $base_image_dir . $request['fileInfo']['IDCARD_FRONT']['_file'], //法人身份证正面
                'IDCARD_BACK' => $base_image_dir . $request['fileInfo']['IDCARD_BACK']['_file'], //法人身份证反面
                'SETTLE_BANKCARD' => $base_image_dir . $request['fileInfo']['SETTLE_BANKCARD']['_file'], //结算银行卡
                'CORP_CODE' => $base_image_dir . $request['fileInfo']['CORP_CODE']['_file'], //营业执照
                'state' => 0,
                'create_time' => date('Y-m-d H:i:s', time()),
                'update_time' => date('Y-m-d H:i:s', time()),
            ]);
            Db::name("merchant_resource_own")->insert([
                'user_id' => $this->user_id,
                'merchant_id' => $merchant_id,
                'IDCARD_FRONT' => $request['fileInfo']['IDCARD_FRONT']['url'], //法人身份证正面
                'IDCARD_BACK' => $request['fileInfo']['IDCARD_BACK']['url'], //法人身份证反面
                'SETTLE_BANKCARD' => $request['fileInfo']['SETTLE_BANKCARD']['url'], //结算银行卡
                'CORP_CODE' => $request['fileInfo']['CORP_CODE']['url'], //营业执照
                'state' => 0,
                'create_time' => date('Y-m-d H:i:s', time()),
                'update_time' => date('Y-m-d H:i:s', time()),
            ]);
            Db::name("merchant_resource_yeepay")->insert([
                'user_id' => $this->user_id,
                'merchant_id' => $merchant_id,
                'state' => 0,
                'create_time' => date('Y-m-d H:i:s', time()),
                'update_time' => date('Y-m-d H:i:s', time()),
            ]);
            Db::name("merchant_resource_thumb")->insert([
                'user_id' =>$this->user_id,
                'merchant_id' => $merchant_id,
                'IDCARD_FRONT' => $base_image_dir . $request['fileInfo']['IDCARD_FRONT']['thumb'], //法人身份证正面
                'IDCARD_BACK' => $base_image_dir . $request['fileInfo']['IDCARD_BACK']['thumb'], //法人身份证反面
                'SETTLE_BANKCARD' => $base_image_dir . $request['fileInfo']['SETTLE_BANKCARD']['thumb'], //结算银行卡
                'CORP_CODE' => $base_image_dir . $request['fileInfo']['CORP_CODE']['thumb'], //营业执照
                'state' => 0,
                'create_time' => date('Y-m-d H:i:s', time()),
                'update_time' => date('Y-m-d H:i:s', time()),
            ]);

            Db::table('business')->where(['business_id' => $this->user_id])->update([
                'is_auth' => 1,
                'business_name' => $request['merFullName'],
                'business_province' => $request['merProvince'],
                'business_city' => $request['merCity'],
                'business_area' => $request['merDistrict'],
                'business_address' => $request['merAddress'],
            ]);

            Db::table('users')->where(['id' => $this->user_id])->update([
                'name' => $request['merShortName'],
            ]);
            Db::table('user_info')->where(['user_id' => $this->user_id ])->update([
                'name' => $request['merShortName'],
            ]);
            Db::commit();
            return ReturnData::ok($merchant_id, '个体资质认证材料上传成功');
        } catch (Exception $e) {
            Db::rollback();
            return ReturnData::error(-1, $e->getMessage());
        }

    }
    /**
     * @Notes:个人认证资质
     * @param Request $request
     * @return array
     * @author: LiBaoJin
     * @Time:
     */
    public function personal_certification(Request $request) {
        $back = ['code'=>666,'msg'=>'ok','data'=>[]];
        $request = $request->post();
        $validate = Loader::validate('PersonalCertification');
        $rule = $validate->check($request);
        if ($rule !== true) {
            $back['code'] = -1;
            $back['msg'] = $validate->getError();
            return $back;
        }
        $detele_data = MerchantService::delete_data($this->user_id);
        if ($detele_data['code'] != '666') {
            return ReturnData::error($detele_data['code'], $detele_data['msg']);
        }
        Db::startTrans();
        try {
            $yeepay = Config::get('yeepay');
            $merchant_identify_email = Config::get('merchant_identify_email');
            $base_image_dir = Config::get('base_image_dir');
            $merchant_id = Db::name("merchant")->insertGetId([
                'user_id' => $this->user_id,
                'requestNo' => md5(time()), //入网请求号
                'type' => 1, // 个人
                'parentMerchantNo' => $yeepay['parentMerchantNo'], //商户编号
                'legalName' => $request['legalName'], //法人姓名
                'legalIdCard' => $request['legalIdCard'], //法人身份证号
                'merLevel1No' => '102', //商户一级分类编码
                'merLevel2No' => '102002', //商户二级分类编码
                'merProvince' => $request['merProvince'], //商户经营地址所在省
                'merCity' => $request['merCity'], //商户经营地址所在市
                'merDistrict' => $request['merDistrict'], //商户经营地址所在区
                'merAddress' => $request['merAddress'], //商户经营地址所在具体地址
                'merLegalPhone' => $request['merLegalPhone'], //商户联系人手机
                //'merShortName' => $request['merShortName'], //商户名称/简称
                'merLegalEmail' => $merchant_identify_email, //商户联系人邮箱
                'headBankCode' => $request['headBankCode'], //开户银行总行编码
                'bankCode' => $request['bankCode'], //开户支行编码 bankCode
                'bankProvince' => $request['bankProvince'], //开户省
                'bankCity' => $request['bankCity'], //开户市
                //'merScope' => $request['merScope'], //商户经营范围
                'cardNo' => $request['cardNo'], //银行卡号
                'create_time' => date('Y-m-d H:i:s', time()),
                'update_time' => date('Y-m-d H:i:s', time()),
                'state' => 0,
                'openMini' => 1,
                'logo_url' => isset($request['fileInfo']['logo_url']['url']) ? $request['fileInfo']['logo_url']['url'] : null,
            ]);
            if (!$merchant_id) {
                return ReturnData::error(-1, '系统错误');
            }
            Db::name("merchant_resource")->insert([
                'user_id' => $this->user_id,
                'merchant_id' => $merchant_id,
                'IDCARD_FRONT' => $base_image_dir . $request['fileInfo']['IDCARD_FRONT']['_file'], //法人身份证正面
                'IDCARD_BACK' => $base_image_dir . $request['fileInfo']['IDCARD_BACK']['_file'], //法人身份证反面
                'SETTLE_BANKCARD' => $base_image_dir . $request['fileInfo']['SETTLE_BANKCARD']['_file'], //结算银行卡
                'HAND_IDCARD' => $base_image_dir . $request['fileInfo']['HAND_IDCARD']['_file'], //手持身份证
                'HAND_BANKCARD' => $base_image_dir . $request['fileInfo']['HAND_BANKCARD']['_file'], //手持银行卡
                'state' => 0,
                'create_time' => date('Y-m-d H:i:s', time()),
                'update_time' => date('Y-m-d H:i:s', time()),
            ]);
            Db::name("merchant_resource_own")->insert([
                'user_id' => $this->user_id,
                'merchant_id' => $merchant_id,
                'IDCARD_FRONT' => $request['fileInfo']['IDCARD_FRONT']['url'], //法人身份证正面
                'IDCARD_BACK' => $request['fileInfo']['IDCARD_BACK']['url'], //法人身份证反面
                'SETTLE_BANKCARD' => $request['fileInfo']['SETTLE_BANKCARD']['url'], //结算银行卡
                'HAND_IDCARD' => $request['fileInfo']['HAND_IDCARD']['url'], //手持身份证
                'HAND_BANKCARD' => $request['fileInfo']['HAND_BANKCARD']['url'], //手持银行卡
                'state' => 0,
                'create_time' => date('Y-m-d H:i:s', time()),
                'update_time' => date('Y-m-d H:i:s', time()),
            ]);
            Db::name("merchant_resource_yeepay")->insert([
                'user_id' => $this->user_id,
                'merchant_id' => $merchant_id,
                'state' => 0,
                'create_time' => date('Y-m-d H:i:s', time()),
                'update_time' => date('Y-m-d H:i:s', time()),
            ]);
            Db::name("merchant_resource_thumb")->insert([
                'user_id' => $this->user_id,
                'merchant_id' => $merchant_id,
                'IDCARD_FRONT' => $base_image_dir . $request['fileInfo']['IDCARD_FRONT']['thumb'], //法人身份证正面
                'IDCARD_BACK' => $base_image_dir . $request['fileInfo']['IDCARD_BACK']['thumb'], //法人身份证反面
                'SETTLE_BANKCARD' => $base_image_dir . $request['fileInfo']['SETTLE_BANKCARD']['thumb'], //结算银行卡
                'HAND_IDCARD' => $base_image_dir . $request['fileInfo']['HAND_IDCARD']['thumb'], //手持身份证
                'HAND_BANKCARD' => $base_image_dir . $request['fileInfo']['HAND_BANKCARD']['thumb'], //手持银行卡
                'state' => 0,
                'create_time' => date('Y-m-d H:i:s', time()),
                'update_time' => date('Y-m-d H:i:s', time()),
            ]);

            Db::table('business')->where(['business_id' => $this->user_id])->update([
                'is_auth' => 1,
                'business_name' => $request['legalName'],
                'business_province' => $request['merProvince'],
                'business_city' => $request['merCity'],
                'business_area' => $request['merDistrict'],
                'business_address' => $request['merAddress'],
            ]);

            Db::table('users')->where(['id' =>$this->user_id])->update([
                'name' => $request['legalName'],
            ]);
            Db::table('user_info')->where(['user_id' => $this->user_id])->update([
                'name' => $request['legalName'],
            ]);
            Db::commit();
            return ReturnData::ok($merchant_id, '个人资质认证材料上传成功');
        } catch (Exception $e) {
            Db::rollback();
            return ReturnData::error(-1, $e->getMessage());
        }

    }

}